package org.colin.aspect;

import java.util.Map;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.colin.Tools.RedisUtil;
import org.colin.Tools.TokenUtil;
import org.colin.Tools.Tool;
import org.colin.annotation.PermissionCheck;
import org.colin.constant.Constants;
import org.colin.exceptions.NoLoginException;
import org.colin.exceptions.NoPermissionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @desc 权限验证AOP切面实现
 * @author wujiangbo
 * @date 2020年1月3日 下午3:13:06
 */
@Component
@Aspect
public class PermissionCheckAspect {

	@Value("${system.tokenTimeout}")
	private Integer tokenTimeout;

	@Value("${system.permissionFlag}")
	private String permissionFlag;

	@Autowired
	private TokenUtil tokenUtil;

	@Autowired
	private RedisUtil redisUtil;

	@Around("@annotation(permissionCheck)")
	public Object loginCheck(ProceedingJoinPoint joinPoint, PermissionCheck permissionCheck) throws Throwable {
		if (Tool.isBlank(permissionFlag) || "1".equals(permissionFlag)) {
			// 获取当前用户请求头信息中的token信息
			String token = this.tokenUtil.getToken();
			if (Tool.isBlank(token)) {
				throw new NoLoginException("请求头信息中无token，请重新登录");
			}
			String userInfoRedisKey = Constants.REDIS_USER_INFO_KEY + token;
			Map<Object, Object> map = redisUtil.hmget(userInfoRedisKey);
			if (map == null) {
				throw new NoLoginException("无用户信息，请重新登录");
			}
			// 权限验证字符串
			String permission = permissionCheck.permission();
			if (!Tool.isBlank(permission)) {
				// 获取用户权限字符串集合
				String permissionString = (String) map.get(Constants.MAP_PERMISSION_LIST_KEY);
				if (Tool.isBlank(permissionString)) {
					throw new NoPermissionException("暂无操作权限，请联系管理员开通");
				}
				if (!permissionString.contains(permission)) {
					throw new NoPermissionException("暂无操作权限，请联系管理员开通(如已开通，请重新登录)");
				}
			}
		}
		return joinPoint.proceed();
	}

}
